﻿using GPS.MODELS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GPS.DataAccessLayer;
using AutoMapper;
using PagedList;
using GPS.ENTITYS;
using GPS.COMMON;
using System.IO;
using System.Data.Entity;
using System.Text;
using System.Data;


namespace GPS.Controllers.GPS_DanhMuc
{
    public class GPS_DonViHanhChinhController : Controller
    {
        DbContextHelper<GPS_NVContext> _db = Singleton<DbContextHelper<GPS_NVContext>>.Inst;
        //
        // GET: /GPS_HTCapGPLX/
        #region Index
        public ActionResult Index(ViewModelSDONVIHC SearchModel, int? currentPage)
        {
            initialCategorySearchAction(SearchModel);
            
            var entities = _db.Filter<SDONVIHC>(o => (SearchModel.dDVHC_MA == null || o.DVHC_MA.StartsWith(SearchModel.dDVHC_MA))
                                                    && (SearchModel.dDVHC_TEN == null || o.DVHC_TEN.StartsWith(SearchModel.dDVHC_TEN))
                                                    && (SearchModel.dDVHC_ACTIVE == null || o.DVHC_ACTIVE == SearchModel.dDVHC_ACTIVE)
                                                    && (SearchModel.dDVHC_LOAI == null || o.DVHC_LOAI == SearchModel.dDVHC_LOAI)
                                                    && (o.DVHC_MAQL.StartsWith("40")));
            ViewBag.TotalRow = entities.Count();
            var model = new List<SDONVIHC>();
            foreach (var currentEntity in entities)
            {
                model.Add(Mapper.Map<SDONVIHC>(currentEntity));
            }
            var pageIndex = SearchModel.Page ?? 1;
            SearchModel.SearchResults = model.ToPagedList(pageIndex, GPS.COMMON.Constants.PageSize);
            return View(SearchModel);
        }

        [HttpPost]
        public void initialCategorySearchAction(ViewModelSDONVIHC viewModel)
        {
            viewModel.lstDonViHanhChinh = _db.GetAll<SDONVIHC>();
            ViewBag.LstLoaiDonVi = new SelectList(_db.Filter<SLOAICSDT>(o => o.LOAICSDT_LOAI == "DVHC"), "LOAICSDT_MA", "LOAICSDT_TEN");
            ViewBag.LstTinh_ThanhPho = new SelectList(_db.Filter<SDONVIHC>(o => o.DVHC_MAQL == "40"), "DVHC_MA", "DVHC_TEN");
            ViewBag.LstQuan_Huyen = new SelectList(_db.Filter<SDONVIHC>(o => o.DVHC_LOAI == "QU" || o.DVHC_LOAI == "HU" && o.DVHC_MADV.StartsWith("40")),"DVHC_MA", "DVHC_TEN");
            ViewBag.LstXa_Phuong = new SelectList(_db.Filter<SDONVIHC>(o => o.DVHC_LOAI == "XA" || o.DVHC_LOAI == "PH" && o.DVHC_MADV.StartsWith("40")), "DVHC_MA", "DVHC_TEN");
            
        }
        #endregion

        //
        // Create: 
        #region create
        public ActionResult Create()
        {
            initialCategoryCreateAction();
            return View(new CrudModelSDONVIHC());
        }

        [HttpPost]
        public ActionResult Create(CrudModelSDONVIHC model)
        {
            initialCategoryCreateAction();
            if (ModelState.IsValid)
            {
                SDONVIHC _model = new SDONVIHC();
                GPS.COMMON.Helpers.CopyObject<SDONVIHC>(model, ref _model);
                _model.DVHC_MA = GetValue_Indentity();
                //_db.Insert<SDONVIHC>(_model);
                return RedirectToAction("Index");
            }
            return View(model);
        }

      
        public void initialCategoryCreateAction()
        {
            ViewBag.LstLoaiDonVi = new SelectList(_db.Filter<SLOAICSDT>(o => o.LOAICSDT_LOAI == "DVHC"), "LOAICSDT_MA", "LOAICSDT_TEN");
            ViewBag.LstTinh_ThanhPho = new SelectList(_db.Filter<SDONVIHC>(o => o.DVHC_LOAI == "TI" || o.DVHC_LOAI == "TP"), "DVHC_MAQL", "DVHC_TEN");
        }

        public string GetValue_Indentity()
        {
            string value = "";
            Int64 valueMax = _db.DbContext.SDONVIHCs.ToList().Max(e => Convert.ToInt64(e.DVHC_MA));

            value = (valueMax + 1).ToString();
            return value;
        }

        
        #endregion

        //
        // Edit: 
        #region Edit
        public ActionResult Edit(string id)
        {
            CrudModelSDONVIHC _model = new CrudModelSDONVIHC();
            SDONVIHC model = _db.GetOne<SDONVIHC>(o => o.DVHC_MA == id);
            GPS.COMMON.Helpers.CopyObject<CrudModelSDONVIHC>(model, ref _model);
            initialCategoryEditAction(_model);
            return View(_model);
        }
        [HttpPost]
        public ActionResult Edit(CrudModelSDONVIHC model, FormCollection form)
        {
            if (ModelState.IsValid)
            {
                var _model = _db.GetOne<SDONVIHC>(o => o.DVHC_MA == model.DVHC_MA);
                GPS.COMMON.Helpers.CopyObject<SDONVIHC>(model, ref _model);
                _db.Update<SDONVIHC>(_model);
                return RedirectToAction("Index");
            }
            return View(model);
        }
        public void initialCategoryEditAction(CrudModelSDONVIHC view)
        {
            //string selectedValues = _db.GetAll<STRANGTHAI>().Select(x => x.TRANGTHAI_MA = view.LYDO_ACTIVE).FirstOrDefault().ToString();
            //ViewBag.lstActivedll = new SelectList(_db.DbContext.STRANGTHAIs.ToList(), "TRANGTHAI_MA", "TRANGTHAI_TEN", selectedValues);
        }
        #endregion

        #region Detele
        public ActionResult Delete(string id)
        {
            CrudModelSDONVIHC _model = new CrudModelSDONVIHC();
            SDONVIHC model = _db.GetOne<SDONVIHC>(o => o.DVHC_MA == id);
            _db.DeleteItem<SDONVIHC>(model);
            return RedirectToAction("Index");
        }
        #endregion

        [HttpPost]
        public ActionResult getQuan_Huyen(string ma_TP)
        {
            var districts = _db.Filter<SDONVIHC>(d => d.DVHC_MAQL == ma_TP).Select(a => "<option value='" + a.DVHC_MADV + "'>" + a.DVHC_TEN + "</option>");
            return Content(string.Join("", districts));
        }

        #region"Import XML"
        public ActionResult ImportXML()
        {
            return View();
        }


        [HttpPost]
        public ActionResult ImportXML(HttpPostedFileBase fileUpload)
        {
            try
            {
                StringBuilder strValidationError = new StringBuilder(string.Empty);
                string strValiteDataTable = "";
                if (fileUpload != null && fileUpload.ContentLength > 0)
                {
                    string extension = Path.GetExtension(fileUpload.FileName);
                    if (extension.ToUpper().StartsWith(".XML"))
                    {
                        string _filePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/Templates/XML/" + Path.GetFileNameWithoutExtension(fileUpload.FileName) + DateTime.Now.ToString("ddMMyyyyhhMMss") + extension);
                        fileUpload.SaveAs(_filePath);

                        // strValidationError.Append("<span style=\"color:red\">Cột Cấp tàu tại dòng " + (rowIndex + 3).ToString() + " không đúng danh mục quy định!</span> <br/>");

                        //DataTable dt = null;
                        DANH_MUC obj1 = XmlHelper.DeserializeFromXmlFile<DANH_MUC>(_filePath);

                        if (obj1 != null && obj1.DM_DVHCs.Count > 0)
                        {
                            //Insert data:
                            CrudModelSDONVIHC1 _model = null;
                            GPS.GPS_DAL.GPS_DanhMucDAO da = new GPS_DAL.GPS_DanhMucDAO();

                            da.GPS_DANHMUC_DVHC_DELETE();

                            for (int i = 0; i < obj1.DM_DVHCs.Count - 1; i++)
                            {
                                _model = obj1.DM_DVHCs[i];
                                da.GPS_DANHMUC_DVHC_INSERT(_model);
                            }

                            strValidationError.Clear();
                            strValidationError.Append("<span style=\"color:blue\">Import file thành công !</span><br/>");
                            ViewBag.ThongBao = strValidationError.ToString();
                            ViewBag.success = "1";
                        }
                        else
                        {
                            strValidationError.Clear();
                            strValidationError.Append("<span style=\"color:red\">File không có dữ liệu!</span><br/>");
                            ViewBag.ThongBao = strValidationError.ToString();

                        }
                        if (System.IO.File.Exists(_filePath))
                        {
                            System.IO.File.Delete(_filePath);
                        }
                    }
                }

                return View();
            }
            catch(Exception ex)
            {
                throw ex;
            }
            
        }

  
        #endregion
	}
}